package com.daoliuhe.scaffold.filter;

import com.daoliuhe.scaffold.tools.Constants;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 用户强制退出
 * @author 21829
 * @date 2016年8月4日
 */
public class ForceLogoutFilter extends AccessControlFilter {
	
	private static final Logger logger = LoggerFactory.getLogger(ForceLogoutFilter.class);
	
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		logger.debug("isAccessAllowed");
		Session session = getSubject(request, response).getSession(false);
		if (session == null) {
			return true;
		}
		
		Object logoutKey = session.getAttribute(Constants.SESSION_FORCE_LOGOUT_KEY);
		logger.debug("isAccessAllowed, logoutKey:{}", logoutKey);
		boolean isAccess = logoutKey == null;
		logger.debug("isAccessAllowed, isAccess:{}", isAccess);
		return isAccess;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		logger.debug("onAccessDenied");
		try {
            getSubject(request, response).logout();//强制退出
        } catch (Exception e) {/*ignore exception*/}

        String loginUrl = getLoginUrl() + (getLoginUrl().contains("?") ? "&" : "?") + "forceLogout=1";
        logger.debug("onAccessDenied, loginUrl:{}",loginUrl);
        WebUtils.issueRedirect(request, response, loginUrl);
        return false;
	}

}
